<template>
  <div class="app-pro-basicLayout-content-wrap">
    <div class="app-pro-pages-content">
      <div class="app-pro-table-search">
        <el-form :inline="true" :model="formInline" ref="formInline" label-width="120px" size="small" class="form-flex-item">
          <el-row :gutter="20">
            <el-col :xs="12" :sm="10" :md="8" :lg="6">
              <!-- <el-form-item :label="'서비스종류'| language()" prop="service_type">
                <el-select v-model="formInline.service_type" :placeholder="'종류를 선택하십시오.'|language()">
                  <el-option
                    v-for="item in serviceTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item> -->
              <el-form-item :label="'빠른검색'|language" prop="keyword">
                <el-input v-model="formInline.keyword" :placeholder="'검색어를 입력해주세요'|language" @keyup.enter.native="handleSearch"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="6" :sm="6" :md="6" :lg="6">
              <el-form-item>
                <el-button type="primary" size="small" @click="handleSearch">{{'검색' | language}}</el-button>
                <el-button size="small" @click="resetForm('formInline')">{{'초기화' | language}}</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="app-pro-pages-table">
        <div class="main-card">
          <div class="main-table-toolbar">
            <div class="main-table-toolbar-title">
              <div class="main-table-toolbar-title-only">신청 관리</div>
            </div>
            <div class="main-table-toolbar-option">
              <!--
              <el-divider direction="vertical"></el-divider> -->
              <el-link :underline="false" class="main-table-toolbar-item-icon">
                <el-tooltip class="item" effect="dark" :content="'다운로드'|language" placement="top">
                  <i @click="downloadFile('/api/order/index', '신청 관리')"  class="el-icon-download"></i>
                </el-tooltip>
              </el-link>
              <!-- <el-link :underline="false" class="main-table-toolbar-item-icon">
                <el-tooltip class="item" effect="dark" :content="'초기화'|language" placement="top">
                  <i @click="getOrderList()" class="el-icon-refresh-right"></i>
                </el-tooltip>
              </el-link> -->
            </div>
          </div>
          <div class="main-table-wrapper" style="padding: 0">
            <my-table
              :columns="columns"
              :data="data"
              :loading="loading"
              :pagination="pagination"
              :showIndex="true"
              :showSelection="true"
              :cellStyle="{padding: '6px 0'}"
              :headerCellStyle="{background:'rgba(247, 133, 2, 1)',color:'#fff'}"
              @emitSelection="emitSelection"
              @currentChange="currentChange"
              @sortChange="sortChange">
              <template v-slot:edit_status="slotProps">
                <el-tag v-if="slotProps.callback.row.edit_status === 0" effect="dark" size="small">{{'신청대기'| language}}</el-tag>
                <el-tag v-else-if="slotProps.callback.row.edit_status === 1" effect="dark" size="small">{{'임시저장'| language}}</el-tag>
                <el-tag v-else-if="slotProps.callback.row.edit_status === 2" effect="dark" size="small">{{'신청완료'| language}}</el-tag>
                <el-tag v-else type="success" effect="dark" size="small">{{'코칭완료'| language}}</el-tag>
              </template>
              <template v-slot:pay_status="slotProps">
                <el-tag v-if="slotProps.callback.row.pay_status === 0" effect="dark" size="small">{{'결제대기' | language}}</el-tag>
                <el-tag v-else type="success" effect="dark" size="small">{{'결제완료'| language}}</el-tag>
              </template>
              <template v-slot:user="slotProps">
                <div v-for="item in slotProps.callback.row.user" :key="item.id">{{item.name}}</div>
              </template>
              <template v-slot:price="slotProps">
                <el-popover
                  width="600"
                  trigger="hover">
                  <el-table :data="slotProps.callback.row.price">
                    <el-table-column width="150" property="title" :label="'제목' | language"></el-table-column>
                    <el-table-column width="150" property="value" :label="'서비스이름' | language"></el-table-column>
                    <!-- <el-table-column width="100" property="discount" label="서비스종류">
                      <template slot-scope="scope">
                        <span>{{scope.row.server_type.value}}</span>
                      </template>
                    </el-table-column> -->
                    <el-table-column width="100" property="original_price" :label="'원가' | language">
                      <template slot-scope="scope">
                        <span>{{scope.row.original_price | toThousandFilter}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column width="100" property="price" :label="'할인가' | language">
                      <template slot-scope="scope">
                        <span>{{scope.row.price | toThousandFilter}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column width="100" property="discount" :label="'할인율' | language"></el-table-column>
                  </el-table>
                  <el-button slot="reference" size="small">{{'조회'| language}}</el-button>
                </el-popover>
              </template>
              <template v-slot:operation="slotProps">
                <el-button
                  @click.native.prevent="handleShow(slotProps.callback.row)"
                  style="color:#666"
                  type="text">
                  {{'조회'| language}}
                </el-button>
                <el-button
                  @click.native.prevent="handleApplication(slotProps.callback.row)"
                  type="text"
                  style="color:#1890ff">
                  {{ '신청서' | language}}
                </el-button>
                <el-button
                  v-if="!slotProps.callback.row.report"
                  @click.native.prevent="handleUpdate(slotProps.callback.row)"
                  type="text">
                  {{'보고서'| language}}
                </el-button>
                <el-button
                  v-else
                  @click.native.prevent="handleShowReport(slotProps.callback.row)"
                  type="text">
                  {{'보고서 다운'| language}}
                </el-button>
                <el-button
                  @click.native.prevent="handleDownloadResume(slotProps.callback.row)"
                  type="text">
                  {{'이력서 '| language}}
                </el-button>
                <!-- <el-popconfirm
                  title="삭제하시겠습니까"
                  @onConfirm="handleDeleteOrder(slotProps.callback.row.id)"
                  confirmButtonText="확인"
                  cancelButtonText="취소"
                >
                  <el-button
                    slot="reference"
                    type="text"
                    style="color:#f56c6c">
                    {{'삭제'| language}}
                  </el-button>
                </el-popconfirm> -->
              </template>
            </my-table>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      :title="dialogForm.title"
      custom-class="dialog-content"
      :visible.sync="dialogForm.dialogVisible"
      :destroy-on-close="true"
      top="5%"
      width="550px">
      <div class="dialog-body-content">
        <form-page
          :ref-obj.sync="formInfo.ref"
          :data="formInfo.data"
          :field-list="formInfo.fieldList"
          :rules="formInfo.rules"
          :label-width="formInfo.labelWidth"
          :list-type-info="listTypeInfo">
        </form-page>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogForm.dialogVisible = false">{{'취소'| language}}</el-button>
        <el-button size="small" type="primary" @click="handleSubmitOrder">{{'확인'| language}}</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="dialogDetail.title"
      custom-class="dialog-content"
      :visible.sync="dialogDetail.dialogVisible"
      :destroy-on-close="true"
      top="5%"
      width="900px">
      <div class="dialog-body-content">
        <div class="resume-detail-template">
          <div><label>{{'주문번호'|language}}：</label><span>{{dialogDetail.detailData.orderNo}}</span></div>
          <div><label>{{'서비스종류'|language}}：</label><span>{{dialogDetail.detailData.title}}</span></div>
          <div><label>{{'서비스옵션'|language}}：</label><span>{{dialogDetail.detailData.subtitle}}</span></div>
          <div><label>{{'상태'|language}}：</label><span>{{edit_status[dialogDetail.detailData.edit_status] | language}}</span></div>
          <div><label>{{'결제상황'|language}}：</label><span>{{dialogDetail.detailData.pay_status===0?'결제대기':'결제완료' | language}}</span></div>
          <div><label>{{'서비스종류'|language}}：</label><span>{{dialogDetail.detailData.service_type}}</span> </div>
          <div>
            <label>{{'서비스옵션'|language}}：</label>
            <div style="padding-left:20px" v-if="dialogDetail.detailData.service_option">
              <div>제목：{{dialogDetail.detailData.service_option.title}}</div>
              <div>서비스이름：{{dialogDetail.detailData.service_option.value}}</div>
              <div>원가：{{dialogDetail.detailData.service_option.original_price}}</div>
              <div>할인가：{{dialogDetail.detailData.service_option.price}}</div>
              <div>할인율：{{dialogDetail.detailData.service_option.discount}}</div>
              <div>서비스설명：{{dialogDetail.detailData.service_option.describe}}</div>
            </div>
          </div>
          <div><label>{{'결제유형'|language}}：</label><span>{{dialogDetail.detailData.pay_type}}</span> </div>
        </div>
        <el-divider></el-divider>
        <div class="resume-detail-template">
          <div><label>{{'상품가격'|language}}：</label><span>{{dialogDetail.detailData.price}}</span></div>
          <div><label>{{'결제금액'|language}}：</label><span>{{dialogDetail.detailData.paid_amount}}</span></div>
          <div><label>{{'결제번호'|language}}：</label><span>{{dialogDetail.detailData.imp_uid}}</span></div>
          <div><label>{{'결제카드번호'|language}}：</label><span>{{dialogDetail.detailData.apply_num}}</span></div>
        </div>
        <el-divider></el-divider>
        <div class="resume-detail-template">
          <div><label>{{'사용자'|language}}：</label><span>{{dialogDetail.detailData.user_name}}</span></div>
          <div><label>{{'성별'|language}}：</label><span>{{dialogDetail.detailData.sex ===0?'남자':'여성'}}</span></div>
          <div><label>{{'휴대폰 번호'|language}}：</label><span>{{dialogDetail.detailData.phone}}</span></div>
          <div><label>{{'이메일'|language}}：</label><span>{{dialogDetail.detailData.email}}</span></div>
        </div>
        <el-divider></el-divider>
        <div class="resume-detail-template">
          <div><label>{{'코멘트'|language}}：</label><span>{{dialogDetail.detailData.remark}}</span></div>
          <div><label>{{'답변'|language}}：</label><span>{{dialogDetail.detailData.reply}}</span></div>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      :title="dialogDis.title"
      custom-class="dialog-content"
      :visible.sync="dialogDis.dialogVisible"
      :destroy-on-close="true"
      top="5%"
      width="550px">
      <el-divider content-position="left">보고서</el-divider>
      <el-upload
        class="upload-demo"
        action="#"
        accept=".pdf,.ppt,.pptx,.xls,.xlsx,.hwp,.doc,.docx,"
        :http-request="uploadFile"
        :file-list="fileList">
        <el-button size="small" type="primary">보고서 업로드</el-button>
        <div slot="tip" class="el-upload__tip">5MB이하, .pdf, .ppt, .pptx, .doc, .docx, .xls, .xlsx, .hwp 로된 보고서를 업로드해주세요.</div>
      </el-upload>
      <el-divider content-position="left">{{'코멘트' | language}}</el-divider>
      <el-input
        type="textarea"
        style="width:100%"
        :autosize="{ minRows: 5}"
        placeholder="설명을 입력하십시오"
        v-model="dialogDis.remark">
      </el-input>
      <el-button style="margin-left:15px" slot="footer" type="primary" @click="selestInstructor">{{'확인' | language}}</el-button>
    </el-dialog>

    <el-dialog
      :title="dialogApplication.title"
      custom-class="dialog-content"
      :visible.sync="dialogApplication.dialogVisible"
      :destroy-on-close="true"
      top="5%"
      width="1000px">
      <div class="dialog-body-content">
        <div v-if="dialogApplication.listData.length">
          <div v-for="(item,index) in dialogApplication.listData" :key='index' >
            <div style="color:#000" v-html="item.has_one_question.title.replace('/n','<br/>')"></div>
            <div style="padding:10px 0 0 10px">{{item.content}}</div>
            <el-divider></el-divider>
          </div>
        </div>
        <div v-else>
          <div style="padding:30px 0;text-align:center;color:#999">내용 없음</div>
        </div>
        <!-- <div v-if="dialogApplication.listData.length">
          <el-collapse v-model="activeNames">
            <el-collapse-item v-for="(item,index) in dialogApplication.listData" :key='index' :title="item.has_one_question.title" :name="index">
              <div style="padding-left:10px">{{item.content}}</div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <div v-else>
          <div style="padding:30px 0;text-align:center;color:#999">내용 없음</div>
        </div> -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { publicEvents } from '@/mixins'
import { getDictData, downloadFile } from '@/api/app'
import { mergeObjOfValue, deepClone } from '@/utils'
import FormPage from '_c/FormPage'
import myTable from '_c/Table'
import * as OrderApi from '@/api/coaching_order/index'
import * as userApi from '@/api/setting/user'
const formInfoData = {
  id: '',
  is_public: '',
  is_important: ''
}
export default {
  name: 'coaching_order',
  data () {
    return {
      formInline: {
        // service_type: '',
        keyword: ''
      },
      serviceTypeOptions: [],
      columns: [{
        label: '주문번호',
        prop: 'orderNo',
        width: 100,
        sortable: true
      }, {
        label: '신청서',
        prop: 'edit_status',
        width: 95,
        slot: 'edit_status',
        sortable: true
      }, {
        label: '상태',
        prop: 'pay_status',
        width: 80,
        slot: 'pay_status',
        sortable: true
      },
      // {
      //   label: '메인타이틀',
      //   prop: 'title'
      // }, {
      //   label: '서브타이틀',
      //   prop: 'subtitle'
      // },
      // {
      //   label: '서비스종류',
      //   prop: 'server_type.value'
      // }, {
      //   label: '서비스옵션',
      //   prop: 'service_option.value'
      // },
      {
        label: '서비스종류',
        prop: 'server_type.value',
        width: 120,
        sortable: true
      }, {
        label: '서비스옵션',
        prop: 'service_option.value',
        width: 120,
        sortable: true
      },
      // {
      //   label: '결제유형',
      //   prop: 'pay_type.value',
      //   sortable: true
      // }, {
      //   label: '상품가격',
      //   prop: 'price',
      //   width: 100,
      //   sortable: true
      // }, {
      //   label: '결제금액',
      //   prop: 'paid_amount',
      //   sortable: true
      // },
      {
        label: '이름',
        prop: 'user.name',
        sortable: true
        // slot: 'user'
      }, {
        label: '등록시간',
        prop: 'created_at',
        width: 160,
        sortable: true
      },
      // {
      //   label: 'word',
      //   prop: 'Word_grade'
      // }, {
      //   label: 'HWP',
      //   prop: 'HWP_grade'
      // },
      {
        label: '관리',
        prop: '',
        width: 250,
        align: 'left',
        slot: 'operation'
      }],
      data: [],
      pagination: {
        currentPage: 1,
        pageSize: 15
      },
      selectionData: [],
      loading: true,
      dialogForm: {
        dialogVisible: false,
        title: '신규등록'
      },
      dialogDetail: {
        dialogVisible: false,
        title: '상세내용',
        detailData: {}
      },
      dialogDis: {
        dialogVisible: false,
        title: '보고서 업로드',
        order_id: '',
        report: '',
        remark: ''
      },
      dialogApplication: {
        dialogVisible: false,
        title: '신청서',
        listData: []
      },
      listTypeInfo: {
        is_public: [{
          label: '공개',
          value: 1
        }, {
          label: '비공개',
          value: 0
        }],
        is_important: [{
          label: '예',
          value: 1
        }, {
          label: '아니요',
          value: 0
        }]
      },
      formInfo: {
        ref: null,
        data: formInfoData,
        fieldList: [
          { label: '공개', value: 'is_public', width: '260', type: 'radio', list: 'is_public', className: 'el-form-block' },
          { label: '주요인재', value: 'is_important', width: '260', type: 'radio', list: 'is_important', className: 'el-form-block' }
        ],
        rules: {},
        labelWidth: '150px'
      },
      edit_status: ['신청대기', '임시저장', '신청완료', '코칭완료'],
      instructorList: [],
      formDate: '',
      activeNames: [],
      fileList: [],
      sortParams: {}
    }
  },
  components: {
    myTable,
    FormPage
  },
  mixins: [publicEvents],
  mounted () {
    this.formDate = new FormData()
    this.formInfo.data = deepClone(formInfoData)
    this.getCoachingService('CoachingService')
    this.getInstructorList()
    this.getOrderList()
    this.initRules()
  },
  methods: {
    initRules () {
      const formInfo = this.formInfo
      formInfo.rules = this.$initRules(formInfo.fieldList)
    },
    getCoachingService (key) {
      getDictData(key).then(res => {
        this.serviceTypeOptions = res.map(item => {
          return {
            label: item.value,
            value: parseInt(item.idx)
          }
        })
      })
    },
    getOrderList () {
      const data = {
        ...this.formInline,
        ...this.sortParams,
        page: this.pagination.currentPage,
        per: this.pagination.pageSize
      }
      this.loading = true
      OrderApi.getCoach(data).then(res => {
        this.loading = false
        this.data = res.data
        this.pagination.total = res.meta.pagination.total
      }).catch(() => {
        this.loading = false
      })
    },
    sortChange (val) {
      this.pagination.currentPage = 1
      let orderBy = val.prop
      if (val.prop.indexOf('.') > 0) {
        const arr = val.prop.split('.')
        orderBy = arr[0]
      }
      if (val.order === 'ascending') {
        this.sortParams = {
          sort: 'asc',
          order_by: orderBy
        }
      } else if (val.order === 'descending') {
        this.sortParams = {
          sort: 'desc',
          order_by: orderBy
        }
      } else {
        this.sortParams = {}
      }
      this.getOrderList()
    },
    handleUpdate (row) {
      this.dialogDis.dialogVisible = true
      this.dialogDis.order_id = row.id
    },
    getInstructorList () {
      userApi.getUserList({ is_instructor: 1, per: 1000 }).then(res => {
        this.instructorList = res.data.map(item => {
          return {
            value: item.id,
            label: item.name
          }
        })
      })
    },
    handleShowReport (rowData) {
      if (rowData.user.name) {
        downloadFile({ id: rowData.report, type: 1, name: rowData.user.name }).then(res => {
          if (res.data.type !== 'application/json') {
            let fileName = decodeURIComponent(res.headers.filename)
            fileName = fileName.replace(/\+/g, ' ')
            const blob = new Blob([res.data], { type: res.data.type })
            if (window.navigator.msSaveOrOpenBlob) {
              navigator.msSaveBlob(blob, fileName)
            } else {
              var link = document.createElement('a')
              link.href = window.URL.createObjectURL(blob)
              link.download = fileName
              link.click()
              window.URL.revokeObjectURL(link.href)
            }
          }
        })
      }
    },
    handleDownloadResume (rowData) {
      if (rowData.user.name) {
        downloadFile({ id: rowData.resume, type: 0, name: rowData.user.name }).then(res => {
          if (res.data.type !== 'application/json') {
            let fileName = decodeURIComponent(res.headers.filename)
            fileName = fileName.replace(/\+/g, ' ')
            const blob = new Blob([res.data], { type: res.data.type })
            if (window.navigator.msSaveOrOpenBlob) {
              navigator.msSaveBlob(blob, fileName)
            } else {
              var link = document.createElement('a')
              link.href = window.URL.createObjectURL(blob)
              link.download = fileName
              link.click()
              window.URL.revokeObjectURL(link.href)
            }
          } else {
            this.$message({
              message: '업로드한 이력서가 없습니다.',
              type: 'warning'
            })
          }
        })
      }
    },
    handleApplication (rowData) {
      this.dialogApplication.dialogVisible = true
      this.dialogApplication.listData = rowData.order_answers
      this.activeNames = [...new Array(rowData.order_answers.length).keys()]
    },
    selestInstructor () {
      if (this.dialogDis.report) {
        this.formDate.set('order_id', this.dialogDis.order_id)
        this.formDate.set('report', this.dialogDis.report)
        this.formDate.set('remark', this.dialogDis.remark)
        OrderApi.updateReport(this.formDate).then(res => {
          this.$message({
            message: '반영이 완료되었습니다.',
            type: 'success'
          })
          this.dialogDis = {
            dialogVisible: false,
            title: '보고서 업로드',
            order_id: '',
            report: ''
          }
          this.getOrderList()
        })
      } else {
        this.$message({
          message: '보고서 업로드',
          type: 'warning'
        })
      }
    },
    handleDeleteOrder (id) {
      OrderApi.deleteOrder({ id }).then(res => {
        this.$message({
          message: '삭제되였습니다.',
          type: 'success'
        })
        this.getOrderList()
      })
    },
    confirmAddOrder () {
      this.dialogForm.title = '신규등록'
      mergeObjOfValue(this.formInfo.data, formInfoData)
      this.dialogForm.dialogVisible = true
    },
    handleSubmitOrder () {
      // if (this.formInfo.data.id) {
      //   OrderApi.updateOrderStatus(this.formInfo.data).then(res => {
      //     this.$message({
      //       message: '수정되였습니다.',
      //       type: 'success'
      //     })
      //     this.getOrderList()
      //     this.dialogForm.dialogVisible = false
      //   })
      // }
    },
    handleEdit (rowData) {
      this.dialogForm.title = '이력서 상태 수정하기'
      this.formInfo.data.id = rowData.id
      mergeObjOfValue(this.formInfo.data, rowData)
      this.dialogForm.dialogVisible = true
    },
    handleShow (rowData) {
      this.dialogDetail.dialogVisible = true
      OrderApi.detailOrder({ id: rowData.id }).then(res => {
        this.dialogDetail.detailData = res
      })
    },
    handleSearch () {
      this.pagination.currentPage = 1
      this.getOrderList()
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.getOrderList()
    },
    emitSelection (val) {
      this.selectionData = val
    },
    currentChange (val) {
      this.pagination.currentPage = val
      this.getOrderList()
    },
    uploadFile (file) {
      const isLt5M = file.file.size / 1024 / 1024 < 5
      console.log(file.file)
      if (!isLt5M) {
        this.$message({
          message: '업로드 실패하였습니다. 5MB 이하의 파일을 첨부해주세요.',
          type: 'warning'
        })
        this.fileList = []
        return
      }
      const _URL = window.URL || window.webkitURL
      this.imageUrl = _URL.createObjectURL(file.file)
      this.dialogDis.report = file.file
    }
  }
}
</script>
